import sys
import os

import requests

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.db.FCDB import FCDB
from src.db.LocalDb import LocalDb
from src.utils.CommonUtils import cleanScreen
from src.utils.LogUtils import Logger
from src.config.CcxInsightConfig import Profile


class SyncOnlineMedia:
    def __init__(self, logger: Logger, localDb: LocalDb):
        self.logger = logger
        self.localDb = localDb
        self.size = 1000

    def __queryMaxSyncTime__(self):
        sql = f"""
            select max(sync_time) as maxSyncTime from online_media
        """
        r = self.localDb.QueryOne(sql)
        if r is None or r["maxSyncTime"] is None:
            return ""
        return r["maxSyncTime"]

    def __queryOnlineMediaData__(self, maxSyncTime, page) -> dict:
        postBody = {
            "meetingName": None,
            "beginDate": maxSyncTime,
            "endDate": None,
            "current": page,
            "size": 50
        }
        headers = {"X-CCXI-EXTERNAL-Token": Profile.token}
        try:

            response = requests.post(url=Profile.bondNewValuationData, data=postBody, headers=headers)
            if response is None or response.status_code != 200:
                self.logger.error(f"API调用失败 url:{Profile.bondNewValuationData}, token:{Profile.token} HTTP_STATUS：{response.status_code}")
                return None

            apiResult = response.json()
            if apiResult["code"] != 1:
                self.logger.error(f"API调用失败 url:{Profile.bondNewValuationData}, token:{Profile.token}, message:{apiResult['msg']}")
            return apiResult["result"]
        except Exception as e:
            self.logger.error(f"API调用异常 url:{Profile.bondNewValuationData}, token:{Profile.token}", e)
        return None

    def __updateLocal__(self, updateDatas):
        sql = """
            REPLACE INTO online_media
            (id,meetingName,dataType,meetingDate,lecturer,
            lecturerSynopsis,meetingContent,videoLong,coverUrl,broadcastUrl,
            publishStatus,isPay,publishTime,meetingType,subjectType)
            VALUES(%(id)s,%(meetingName)s,%(dataType)s,%(meetingDate)s,%(lecturer)s,
            %(lecturerSynopsis)s,%(meetingContent)s,%(videoLong)s,%(coverUrl)s,%(broadcastUrl)s,
            %(publishStatus)s,%(isPay)s,%(publishTime)s,%(meetingType)s,%(subjectType)s);     
        """
        return self.localDb.ExecMany(sql, updateDatas)

    def sync(self):
        total = 0
        page = 1

        maxSyncTime = self.__queryMaxSyncTime__()
        self.logger.info(f"最后更新时间 {maxSyncTime}")

        while True:
            result = self.__queryOnlineMediaData__(maxSyncTime=maxSyncTime, page=page)
            if result is not None:
                dataList = result["dataList"]
                self.logger.info(f"加载数据 {len(dataList)} 条")
                self.__updateLocal__(updateDatas=dataList)
                total += len(dataList)
                self.logger.info(f"更新 {len(dataList)}，合计更新 {total}")
                if not result["hasNext"]:
                    break
                page += 1


def main():
    logger = Logger()
    cleanScreen()
    logger.info("============投资者服务的多媒体视频 开始================")

    localDb = LocalDb(logSql=False, autocommit=True)

    sync = SyncOnlineMedia(logger=logger, localDb=localDb)
    sync.sync()
    logger.info("============投资者服务的多媒体视频 结束================")


# 程序入口
if __name__ == "__main__":
    main()
